package native

import (
	"fmt"
	"gitee.com/zy_blue7/go-gorm-learn/insert"
	"gorm.io/gorm"
)

// todo https://gorm.io/zh_CN/docs/sql_builder.html

// NativesScan 原生查询 SQL 和 Scan
func NativesScan(db *gorm.DB) {

	type Result struct {
		ID   int
		Name string
		Age  int
	}

	var result Result
	db.Debug().Raw("SELECT id, name, age FROM users WHERE age = ?", 18).Scan(&result)
	fmt.Println(result) // {1 hello 18}
	db.Debug().Raw("SELECT id, name, age FROM users WHERE age = ?", 20).Scan(&result)
	fmt.Println(result) //  {24 jinzhu_2 20}

	var age int
	db.Raw("SELECT SUM(age) FROM users WHERE name = ?", "hello").Scan(&age)
	fmt.Println(age) // 379

	// Exec 原生 SQL
	// todo db.Exec("DROP TABLE users")
	// todo db.Exec("UPDATE orders SET shipped_at = ? WHERE id IN ?", time.Now(), []int64{1, 2, 3})

	// Exec with SQL Expression
	// todo db.Exec("UPDATE users SET money = ? WHERE name = ?", gorm.Expr("money * ? + ?", 10000, 1), "jinzhu")
}

func NativesOther(db *gorm.DB) {

	var user insert.User
	// todo tryrun  在不执行的情况下生成 SQL 及其参数，可以用于准备或测试生成的 SQL
	stmt := db.Session(&gorm.Session{DryRun: true}).First(&user, 1).Statement
	fmt.Println(stmt.SQL.String()) // SELECT * FROM `users` WHERE `users`.`id` = ? AND `users`.`deleted_at` IS NULL ORDER BY `users`.`id` LIMIT 1
	fmt.Println(stmt.Vars)         // [1]
}
